<?php
/**
 * @auther:周卫星
 * @className:UploadController.php
 * @projectName:train
 * @classDesc:
 * @date:2019/10/29
 * @time:16:53
 */

namespace App\Http\Controllers\common;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UploadController extends Controller
{
    /**
     * 上传图片
     * @param Request $request
     * @return UploadController
     */
    public function uploadImage(Request $request)
    {
        if ($request -> isMethod('post')){
            // 获取是图片类型
            $img_type = $request -> post('type');

            $save_path = $img_type.date("Y-m-d", time());
            $path = $request -> file('file') -> store("public/".$save_path);
            $path_arr = explode('/', $path);
            unset($path_arr[0]);
            $return_path = 'storage/'.implode('/', $path_arr);
            if ($path){
                $result = [
                    'code' => 0,
                    'msg' => '上传成功',
                    'data' => [
                        'src' => asset($return_path),
                        '_token' => csrf_token()
                    ]
                ];
            }else{
                $result = [
                    'code' => 1,
                    'msg' => '上传失败',
                    'data' => [
                        '_token' => csrf_token()
                    ]
                ];
            }
            return $this -> returnJson($result);
        }
    }

    /**
     * 富文本编辑器图片上传
     * @param Request $request
     * @return UploadController
     */
    public function uploadEditor(Request $request)
    {
        if ($request -> isMethod('post')){
            $type = 'editor';
            $save_path = $type.'/'.date('Y-m-d', time());
            $path = $request -> file('editormd-image-file') -> store('public/'.$save_path);
            $path_arr = explode('/', $path);
            unset($path_arr[0]);
            $return_path = 'storage/'.implode('/', $path_arr);
            if ($path){
                $result = [
                    'success' => (int)1,
                    'message' => '上传成功',
                    'url' => asset($return_path)
                ];
            }else{
                $result = [
                    'success' => (int)0,
                    'message' => '上传失败',
                    'url' => null
                ];
            }
            return $this -> returnJson($result);
        }
    }
}
